// 注意：此文件不再依赖环信SDK，而是基于Socket.IO实现
// 保留WebIM对象定义，保持向后兼容
let WebIM = {};

// 1. 获取userStatusService实例
let userStatusService = null;

// 2. 初始化WebIM
function initWebIM() {
  // 检查是否已经初始化
  if (WebIM.conn) {
    return WebIM;
  }
  
  try {
    // 动态加载userStatusService
    const userStatusServiceModule = require('./userStatusService.js');
    userStatusService = userStatusServiceModule.default || userStatusServiceModule;
    
    // 创建模拟的conn对象，保持API兼容性
    WebIM.conn = {
      // 消息ID生成器
      getUniqueId: function() {
        return Date.now() + '_' + Math.random().toString(36).substr(2, 9);
      },
      
      // 发送消息方法
      send: function(message) {
        console.log('WebIM发送消息:', message);
        
        // 调用userStatusService发送消息
        return userStatusService.sendMessage('chat-message', {
          type: message.type,
          to: message.to,
          from: message.from,
          content: message.body,
          id: message.id || WebIM.conn.getUniqueId(),
          timestamp: Date.now()
        });
      },
      
      // 上下文对象，保持兼容性
      context: {
        userId: uni.getStorageSync('userId') || '',
        accessToken: uni.getStorageSync('token') || ''
      },
      
      // 模拟环信SDK的监听方法
      addEventHandler: function(eventName, handler) {
        console.log('添加事件处理器:', eventName);
        // 这里可以根据需要实现事件监听逻辑
      },
      
      // 模拟登录方法
      open: function(options) {
        console.log('WebIM模拟登录:', options);
        // 实际上使用userStatusService进行连接
        userStatusService.initWebSocket();
        
        // 保存用户信息到上下文
        this.context.userId = options.user; 
        return Promise.resolve({ data: { access_token: options.accessToken } });
      },
      
      // 模拟断开连接
      close: function() {
        console.log('WebIM模拟断开连接');
        if (userStatusService) {
          userStatusService.close();
        }
      },
      
      // 其他必要的兼容性方法
      listGroupMember: function(options) {
        console.log('获取群成员:', options);
        // 实现获取群成员的逻辑
        if (options.success) {
          options.success({ data: [] });
        }
      }
    };
    
    // 配置对象
    WebIM.config = {
      appkey: "easemob-demo#easeim",
      apiURL: "https://a1.easemob.com",
      xmppURL: 'wss://im-api-wechat.easemob.com/websocket',
      isDebug: false
    };
    
    // 消息类型常量
    WebIM.msgType = {
      TEXT: 'txt',
      IMAGE: 'img',
      AUDIO: 'audio',
      VIDEO: 'video',
      LOCATION: 'location',
      FILE: 'file',
      CUSTOM: 'custom'
    };
    
    // 创建消息的工厂方法
    WebIM.message = function(type, id) {
      const msg = {
        id: id || WebIM.conn.getUniqueId(),
        type: type,
        body: {},
        set: function(options) {
          // 设置消息属性
          this.body = options.body || {};
          this.from = options.from || WebIM.conn.context.userId;
          this.to = options.to;
          this.chatType = options.chatType || 'singleChat';
          this.roomType = options.roomType || false;
          this.success = options.success;
          
          // 如果是群组聊天，设置群组属性
          if (options.chatType === 'groupChat') {
            this.setGroup = function() {
              this.roomType = true;
            };
          }
        }
      };
      return msg;
    };
    
  } catch (error) {
    console.error('初始化WebIM失败:', error);
  }
  
  return WebIM;
}

// 3. 初始化WebIM
initWebIM();

// 4. 添加Emoji相关功能
WebIM.parseEmoji = function(msg) {
  if (typeof WebIM.Emoji === "undefined" || typeof WebIM.Emoji.map === "undefined") {
    return msg;
  }

  var emoji = WebIM.Emoji,
    reg = null;
  var msgList = [];
  var objList = [];

  for (var face in emoji.map) {
    if (emoji.map.hasOwnProperty(face)) {
      while (msg.indexOf(face) > -1) {
        msg = msg.replace(face, "^" + emoji.map[face] + "^");
      }
    }
  }

  var ary = msg.split("^");
  var reg = /^e.*g$/;

  for (var i = 0; i < ary.length; i++) {
    if (ary[i] != "") {
      msgList.push(ary[i]);
    }
  }

  for (var i = 0; i < msgList.length; i++) {
    if (reg.test(msgList[i])) {
      var obj = {};
      obj.data = msgList[i];
      obj.type = "emoji";
      objList.push(obj);
    } else {
      var obj = {};
      obj.data = msgList[i];
      obj.type = "txt";
      objList.push(obj);
    }
  }

  return objList;
};

// 5. 添加其他辅助方法
WebIM.time = function() {
  var date = new Date();
  var Hours = date.getHours();
  var Minutes = date.getMinutes();
  var Seconds = date.getSeconds();
  var time = date.getFullYear() + "-" + (date.getMonth() + 1) + "-" + date.getDate() + " " + (Hours < 10 ? "0" +
    Hours : Hours) + ":" + (Minutes < 10 ? "0" + Minutes : Minutes) + ":" + (Seconds < 10 ? "0" + Seconds :
    Seconds);
  return time;
};

// 6. 添加Emoji对象定义
WebIM.Emoji = {
  path: "../static/images/faces/",
  map: {
    ":[):]": "ee_1.png",
    ":[D]": "ee_2.png",
    ";)": "ee_3.png",
    ":[o]": "ee_4.png",
    ":[p]": "ee_5.png",
    "[(H)]": "ee_6.png",
    ":[@]": "ee_7.png",
    ":[s]": "ee_8.png",
    ":[$$]": "ee_9.png",
    ":[(]": "ee_10.png ",
    "['(]": "ee_11.png ",
    "[<o)]": "ee_12.png",
    "[(a)]": "ee_13.png",
    "[8o|]": "ee_14.png ",
    "[8-|]": "ee_15.png ",
    "[+o(]": "ee_16.png ",
    "[|-)]": "ee_17.png",
    ":[|]": "ee_18.png",
    "[*-)]": "ee_19.png",
    ":[#]": "ee_20.png",
    "[^o)]": "ee_21.png",
    ":[*]": "ee_22.png",
    "[8-)]": "ee_23.png",
    "[del]": "btn_del.png",
    "[(|)]": "ee_24.png",
    "[(u)]": "ee_25.png",
    "[(S)]": "ee_26.png",
    "[(*)]": "ee_27.png",
    "[(#)]": "ee_28.png",
    "[(R)]": "ee_29.png",
    "[({)]": "ee_30.png",
    "[(})]": "ee_31.png",
    "[(k)]": "ee_32.png",
    "[(F)]": "ee_33.png",
    "[(W)]": "ee_34.png",
    "[(D)]": "ee_35.png"
  }
};

// 7. 导出WebIM对象
export default WebIM;
module.exports = WebIM;
